import json
from again.Welcome.home import Ui_Home  # 替换 'again.home' 为实际的 UI 文件名
from again.Welcome.loading_screen_new import Ui_Form
from PyQt6.QtGui import QGuiApplication, QPixmap, QMouseEvent, QMoveEvent
from PyQt6 import QtWidgets, QtCore
import sys
import os
from datetime import datetime
from PyQt6.QtCore import Qt, QTimer, QCoreApplication, QEvent
from new_project_main import NewProject  # 导入new_project_main
from again.main.Welcome_main.GeneralSetting_main import GeneralSettingsWin  # 导入new_project_main
from PyQt6.QtWidgets import *
import picture.resources_rc

class LoadingWin(QWidget):
    def __init__(self):
        super(LoadingWin, self).__init__()

        # 设置边框区域宽度，在此宽度内长按鼠标并拖动可实现缩放
        self.borderWide = 10
        # 初始化窗口
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        # 隐藏窗体顶部
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        # 边框样式
        self.ui.bgFrame.setFrameStyle(QFrame.Shape.Panel)  # 设置QFrame的边框，以便在未点击时能够鼠标追踪事件生效

# 项目数据文件
PROJECTS_FILE = 'projects.json'

def save_projects(projects):
    with open(PROJECTS_FILE, 'w', encoding='utf-8') as f:
        json.dump(projects, f, indent=4, ensure_ascii=False)

def load_projects():
    if os.path.exists(PROJECTS_FILE):
        with open(PROJECTS_FILE, 'r', encoding='utf-8') as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return []
    return []


class ListDeleteButtonWidget(QtWidgets.QWidget):
    signal_delItem = QtCore.pyqtSignal(int)  # 删除item信号

    def __init__(self, row):
        super(ListDeleteButtonWidget, self).__init__()

        self.setObjectName("widgetProjectBtn")
        horizontalLayout = QtWidgets.QHBoxLayout(self)
        horizontalLayout.setObjectName("horizontalLayout")
        pBtnProjectDelete = QtWidgets.QPushButton(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(pBtnProjectDelete.sizePolicy().hasHeightForWidth())
        pBtnProjectDelete.setSizePolicy(sizePolicy)
        pBtnProjectDelete.setObjectName("pBtnProjectDelete")
        horizontalLayout.addWidget(pBtnProjectDelete)
        pBtnProjectDelete.setText("删除")
        pBtnProjectDelete.setStyleSheet("""
                    QPushButton {
                        background-color: #ff4d4d;
                        color: white;
                    }
                    QPushButton:hover {
                        background-color: #ff1a1a;
                    }
                    QPushButton:pressed {
                        background-color: #e60000;
                    }

                """)

        self.row = row  # 按钮所对应的项目编号
        pBtnProjectDelete.clicked.connect(self.deleteProjectEmit)
        pBtnProjectDelete.setCursor(QtCore.Qt.CursorShape.PointingHandCursor)

    def deleteProjectEmit(self):
        self.signal_delItem.emit(self.row)  # 发送要删除的project的编号信号

class ListOpenButtonWidget(QtWidgets.QWidget):
    signal_openItem = QtCore.pyqtSignal(int)  # 打开item信号

    def __init__(self, row):
        super(ListOpenButtonWidget, self).__init__()

        self.setObjectName("widgetProjectBtn")
        horizontalLayout = QtWidgets.QHBoxLayout(self)
        horizontalLayout.setObjectName("horizontalLayout")
        pBtnProjectOpen = QtWidgets.QPushButton(self)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Fixed, QtWidgets.QSizePolicy.Policy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(pBtnProjectOpen.sizePolicy().hasHeightForWidth())
        pBtnProjectOpen.setSizePolicy(sizePolicy)
        pBtnProjectOpen.setObjectName("pBtnProjectOpen")
        horizontalLayout.addWidget(pBtnProjectOpen)
        pBtnProjectOpen.setText("打开")
        pBtnProjectOpen.setStyleSheet("""
                    QPushButton {
                        background-color: #4a90e8;
                        color: #ebf6ff;
                    }
                    QPushButton:hover {
                        background-color: #4a80e2;
                    }
                    QPushButton:pressed {
                        background-color: #4973dc;
                    }
                """)
        self.row = row  # 按钮所对应的项目编号
        pBtnProjectOpen.clicked.connect(self.openProjectEmit)
        pBtnProjectOpen.setCursor(QtCore.Qt.CursorShape.PointingHandCursor)

    def openProjectEmit(self):
        self.signal_openItem.emit(self.row)  # 发送要打开的project的编号信号




class HomeWin(QMainWindow):
    def __init__(self):
        super(HomeWin, self).__init__()
        self.ui = Ui_Home()  # 创建Ui_Home对象
        self.ui.setupUi(self)  # 设置Ui_Home对象
        self.setup_table()  # 调用设置表格方法

        # 窗口设置
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)  # 隐藏窗体顶部
        self.setMouseTracking(True)  # 设置鼠标追踪

        # 拖动相关变量
        self.is_maximized = False
        self.initDrag()
        self.initial_geometry = self.geometry()  # 记录初始位置和大小

        # 窗口控制按钮
        self.ui.pBtnClose.clicked.connect(self.close)
        self.ui.pBtnBig.clicked.connect(self.toggle_maximize)
        self.ui.pBtnSmall.clicked.connect(self.showMinimized)

        # 加载项目
        self.projects = load_projects()
        self.filtered_projects = self.projects  # 保持当前的过滤结果
        self.populate_table()

        # 连接 tableWidgetList 的点击事件到槽函数
        self.ui.tableWidgetList.itemClicked.connect(self.on_item_clicked)
        self.selected_project = None
        # 连接按钮
        self.ui.pBtnNew.clicked.connect(self.new_project)
        self.ui.pBtnOpen.clicked.connect(self.open_project)

        # 创建菜单
        self.createMenus()

        # 连接搜索栏
        self.ui.lineEditSearch.textChanged.connect(self.search_projects)

    def on_item_clicked(self, item):
        row = item.row()
        if 0 <= row < len(self.projects):
            self.selected_project = self.projects[row]
        else:
            self.selected_project = None
            print("Selected row is out of range.")
    def setup_table(self):
        # 禁用列宽调整
        header = self.ui.tableWidgetList.horizontalHeader()
        header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeMode.Fixed)

        # 设置列宽
        self.set_column_widths([100, 300, 300, 150, 80])

    def set_column_widths(self, widths):
        for i, width in enumerate(widths):
            self.ui.tableWidgetList.setColumnWidth(i, width)

    def createMenus(self):
        # 创建文件菜单
        self.fileMenu = QtWidgets.QMenu(self)
        self.newProjectAction = self.fileMenu.addAction("新建项目")
        self.openProjectAction = self.fileMenu.addAction("打开项目")
        self.exitAction = self.fileMenu.addAction("退出")

        # 连接文件菜单项到槽函数
        self.newProjectAction.triggered.connect(self.new_project)
        self.openProjectAction.triggered.connect(self.open_project)
        self.exitAction.triggered.connect(self.exitApp)

        # 将文件菜单连接到文件按钮
        self.ui.pBtnFile.setMenu(self.fileMenu)

        # 类似地为其他菜单创建动作
        self.settingsMenu = QtWidgets.QMenu(self)
        self.settingsAction = self.settingsMenu.addAction("设置选项")
        self.settingsAction.triggered.connect(self.GeneralSetting)
        self.ui.pBtnSetting.setMenu(self.settingsMenu)

        self.helpMenu = QtWidgets.QMenu(self)
        self.aboutAction = self.helpMenu.addAction("关于")
        self.aboutAction.triggered.connect(self.about)
        self.ui.pBtnHelp.setMenu(self.helpMenu)


    def search_projects(self):
        # 获取搜索框中的文本
        search_text = self.ui.lineEditSearch.text().strip().lower()

        # 根据搜索文本过滤项目
        self.filtered_projects = [
            project for project in self.projects
            if search_text in project['name'].lower()
        ]

        # 更新表格
        self.populate_table()

    def populate_table(self):
        self.ui.tableWidgetList.setRowCount(0)
        for idx, project in enumerate(self.filtered_projects):
            self.add_project_to_table(idx, project)

    def add_project_to_table(self, idx, project):
        row_position = self.ui.tableWidgetList.rowCount()
        self.ui.tableWidgetList.insertRow(row_position)

        self.add_item(row_position, 0, QtWidgets.QTableWidgetItem(str(idx + 1)))
        self.add_item(row_position, 1, QtWidgets.QTableWidgetItem(project["name"]))
        self.add_item(row_position, 2, QtWidgets.QTableWidgetItem(project["created_time"]))
        datetime_object = datetime.strptime(project["last_opened_time"], "%Y-%m-%d %H:%M:%S")
        nowTime = datetime.now()
        lastOpenTime = str((nowTime - datetime_object).days) + "天前"
        self.add_item(row_position, 3, QtWidgets.QTableWidgetItem(lastOpenTime))

        open_button = ListOpenButtonWidget(row_position)
        open_button.setMinimumWidth(50)  # 设置最小宽度
        open_button.signal_openItem.connect(self.open_project_by_index)

        delete_button = ListDeleteButtonWidget(row_position)
        delete_button.setMinimumWidth(50)  # 设置最小宽度
        delete_button.signal_delItem.connect(self.delete_project)

        button_widget = QtWidgets.QWidget()
        button_layout = QtWidgets.QHBoxLayout(button_widget)
        button_layout.addWidget(open_button)
        button_layout.addWidget(delete_button)
        button_layout.setContentsMargins(0, 0, 0, 0)  # 设置内边距
        button_layout.setSpacing(10)  # 设置控件间距
        self.ui.tableWidgetList.setCellWidget(row_position, 4, button_widget)

    def add_item(self, row, col, text):
        item = QtWidgets.QTableWidgetItem(text)
        item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)  # 设置内容居中对齐
        self.ui.tableWidgetList.setItem(row, col, item)

    def open_project(self):
        # 确保 selected_project 存在并且项目列表非空
        if not self.projects:
            # 如果没有任何项目，提示用户
            QtWidgets.QMessageBox.warning(self, "错误", "没有可打开的项目")
            return

        # 如果未选择项目，默认打开第一个项目
        project = self.selected_project or self.projects[0]

        # 检查项目数据是否为字典类型
        if not isinstance(project, dict):
            print("Project is not a dict")
            QtWidgets.QMessageBox.warning(self, "错误", "项目数据无效：数据不是字典类型")
            return

        # 弹出文件选择对话框
        file_name, _ = QtWidgets.QFileDialog.getOpenFileName(
            self,
            "选择项目文件",
            project.get("directory", ""),  # 使用项目的目录作为默认路径
            "WSP Files (*.wsp);;JSON Files (*.json);;All Files (*.*)"
        )

        if file_name:
            # 处理选中的文件
            QtWidgets.QMessageBox.information(self, "信息", f"您选择了文件: {file_name}")
            project["last_opened_time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.update_project_in_table(project)
            save_projects(self.projects)

    def open_project_by_index(self, row):
        if 0 <= row < len(self.projects):
            self.selected_project = self.projects[row]
            self.open_project()  # 调用 open_project 方法，不传递参数
        else:
            print("Invalid row index.")

    def update_project_in_table(self, project):
        for row in range(self.ui.tableWidgetList.rowCount()):
            if self.ui.tableWidgetList.item(row, 1).text() == project["name"]:
                self.ui.tableWidgetList.setItem(row, 3, QtWidgets.QTableWidgetItem(project["last_opened_time"]))
                break

    def delete_project(self, row):
        del self.projects[row]
        self.ui.tableWidgetList.removeRow(row)
        save_projects(self.projects)
        self.populate_table()

    def exitApp(self):
        QtWidgets.QApplication.quit()
    #
    # def settings(self):
    #     QtWidgets.QMessageBox.information(self, "设置", "设置选项")

    def about(self):
        QtWidgets.QMessageBox.information(self, "关于", "关于信息")



    def initDrag(self):
        # 设置鼠标跟踪判断扳机默认值
        self.moveDrag = False

    def mousePressEvent(self, event):
        if (
                event.button() == Qt.MouseButton.LeftButton) and not self.toolButtonsUnderMouse() and self.ui.widgetTop.underMouse():
            if self.is_maximized:
                self.toggle_maximize()
                self.moveDragPosition = event.globalPosition().toPoint() - self.geometry().topLeft()
            else:
                self.moveDragPosition = event.globalPosition().toPoint() - self.pos()
            self.moveDrag = True
            event.accept()

    def mouseMoveEvent(self, event):
        if self.moveDrag:
            self.move(event.globalPosition().toPoint() - self.moveDragPosition)
            event.accept()

    def mouseReleaseEvent(self, event):
        self.moveDrag = False

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton and self.ui.widgetTop.underMouse():
            self.toggle_maximize()

    def toolButtonsUnderMouse(self):
        return self.ui.pBtnClose.underMouse() or self.ui.pBtnBig.underMouse() or self.ui.pBtnSmall.underMouse()

    def toggle_maximize(self):
        if self.is_maximized:
            self.setGeometry(self.initial_geometry)
            self.is_maximized = False
        else:
            self.initial_geometry = self.geometry()
            self.showMaximized()
            self.is_maximized = True

    # 页面跳转
    def new_project(self):
        # 显示新建项目页面
        self.newproject_window = NewProject()
        self.newproject_window.show()

    def GeneralSetting(self):
        # 显示通用设置页面
        self.generalsetting_window = GeneralSettingsWin()
        self.generalsetting_window.show()

class CustomSplashScreen(QSplashScreen):
    def __init__(self, pixmap):
        super().__init__(pixmap)

        # 初始化UI
        self.widget = LoadingWin()
        self.lay = QVBoxLayout()
        self.lay.setContentsMargins(0, 0, 0, 0)
        self.lay.addWidget(self.widget)
        self.setLayout(self.lay)

        self.processValue = 0
        self.widget.ui.labelInitialiazing.setText(f"正在初始化界面...\nInitializing...(0%)")

        # 定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.updateInfo)
        self.timer.start(100)  # 每 50 毫秒更新一次

    def updateInfo(self):
        if self.processValue < 100:
            self.processValue += 2  # 每次增加2%，这样总共更新50次，每次50毫秒，总时间2500毫秒
            self.widget.ui.labelInitialiazing.setText(f"正在初始化界面...\nInitializing...({self.processValue}%)")
            QCoreApplication.processEvents()  # 允许主进程处理事件
        else:
            self.timer.stop()
            self.showMyWidget()

    def showMyWidget(self):
        self.mywidget = HomeWin()  # 替换为你的主窗口类
        self.mywidget.show()
        self.close()


    def mousePressEvent(self, a0: QMouseEvent) -> None:
        pass

    def mouseDoubleClickEvent(self, a0: QMouseEvent) -> None:
        pass

    def enterEvent(self, a0: QEvent) -> None:
        pass

    def moveEvent(self, a0: QMoveEvent) -> None:
        pass



if __name__ == '__main__':
    # 自适应高分辨率屏幕（注意放在QApplication创建之前）
    QGuiApplication.setHighDpiScaleFactorRoundingPolicy(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)  # 设置支持小数放大比例（适应如125%的缩放比）
    app = QApplication(sys.argv)

    # 创建一个空的 QPixmap
    empty_pixmap = QPixmap(643, 380)
    empty_pixmap.fill(Qt.GlobalColor.transparent)

    splash = CustomSplashScreen(empty_pixmap)

    splash.show()
    sys.exit(app.exec())

